import Vue from 'vue'
import Vuex from 'vuex'
import { currentUserApi } from '@/Api/UserApi'
import { currentUserMenusApi } from '@/Api/MenuApi'
import createPersistedState from 'vuex-persistedstate'

Vue.use(Vuex)

export default new Vuex.Store({
  state() {
    return {

      user: {},
      menus: []
    }
  },
  getters: {
    tree(state) {
      return loadTree();

      function loadTree() {
        const tree = state.menus.filter(menu => menu.parentId == 0);
        tree.forEach(item => {
          item.children = getTree(item.id)
        })
        return tree;
      }

      function getTree(id) {
        const tree = state.menus.filter(menu => menu.parentId == id);
        tree.forEach(item => {
          item.children = getTree(item.id)
        })
        return tree;
      }
    }
  },
  mutations: {
    //获取当前用户信息
    setCurrentUser(state, { user }) {
      state.user = user;
    },
    //获取菜单信息
    setCurrentUserMenus(state, { menus }) {
      state.menus = menus;
    }
  },
  actions: {
    loadCurrentUserAction({ commit }) {
      return new Promise(async (resolve, reject) => {

        try {
          const res = await currentUserApi()
          if (res.status == 200) {
            const user = res.data;
            commit('setCurrentUser', { user })
            resolve()
          } else {
            reject(res)
          }

        } catch (error) {
          reject(error)

        }
      })
    },
    //获取菜单menus
    loadCurrentUserMenusAction({ commit }, { userId }) {
      return new Promise(async (resolve, reject) => {

        try {
          const res = await currentUserMenusApi(userId)
          if (res.status == 200) {
            const menus = res.data;
            commit('setCurrentUserMenus', { menus })
            resolve()
          } else {
            reject(res)
          }

        } catch (error) {
          reject(error)

        }
      })
    }
  },
  plugins: [
    createPersistedState({
      storage: window.localStorage,
      reducer(state) {
        return JSON.parse(JSON.stringify(state))
      }
    })
  ]

})
